package com.ty.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ty.dao.InventoryBatchDao;
import com.ty.dao.InventoryDao;
import com.ty.dao.OutItemDao;
import com.ty.dao.PoItemDao;
import com.ty.dto.InventoryChangSource;
import com.ty.entity.*;
import com.ty.service.IInvertoryOptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("SALE_OUT")
public class SaleOutServiceImpl implements IInvertoryOptionService {
   @Autowired
   private OutItemDao outItemDao;
    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private InventoryBatchDao inventoryBatchDao;

    @Override
    public void option(InventoryChangSource source) {
        //销售出库业务逻辑
        /** 找到出库单id*/
        String outid = source.getRefId();
        /** 找到出库单*/
        OutItemQuery outItemQuery = new OutItemQuery().setOutId(outid);
        List<OutItem> outItems = outItemDao.select(outItemQuery);

        for (OutItem outItem :outItems){
            InventoryQuery inventoryQuery = InventoryQuery.builder().id(outItem.getProductId()).build();

            List<Inventory> inventoryList =inventoryDao.select(inventoryQuery);

            if (ObjectUtil.isNotEmpty(inventoryList)){
                Inventory inventory0 = inventoryList.get(0);
                inventoryDao.upadeteQty(outItem.getProductId(), outItem.getQty());
            }else {
                Inventory inventory1 =  Inventory.builder().id(outItem.getProductId()).productname(outItem.getProductName())
                        .qty(outItem.getQty()).salecount(outItem.getQty()).version(0).build();
                inventoryDao.insert(inventory1);
            }
            String batchid = "B"+outItem.getProductId()+"-"+ DateUtil.format(outItem.getProductionDate().atStartOfDay(),"yyyyMMdd");
            InventoryBatchQuery batchQuery = InventoryBatchQuery.builder().batchid(batchid).build();
            List<InventoryBatch> batchList = inventoryBatchDao.select(batchQuery);

            if (ObjectUtil.isNotEmpty(batchList)){
                inventoryBatchDao.updateBatchQty(batchid, outItem.getQty());
            }else {
                InventoryBatch inventoryBatch = InventoryBatch.builder()
                        .batchid(batchid)
                        .productid(outItem.getProductId())
                        .productname(outItem.getProductName())
                        .productiondate(outItem.getProductionDate())
                        .biref(outItem.getBrief())
                        .expirydate(outItem.getExpiryDate())
                        .shelfid(outItem.getShelfId())
                        .shelflife(outItem.getShelfLife())
                        .build();
                inventoryBatchDao.insert(inventoryBatch);
            }
        }
    }
}
